package abq2.jic.jic.plugin.operate;

import com.alibaba.fastjson.JSON;

import com.alibaba.fastjson.JSONObject;
import kd.bos.context.RequestContext;


import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.form.gpt.IGPTAction;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.ServiceHelperModule;
import kd.bos.servicehelper.operation.DeleteServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
 *                             _ooOoo_
 *                            o8888888o
 *                            88" . "88
 *                            (| -_- |)
 *                            O\  =  /O
 *                         ____/`---'\____
 *                       .'  \\|     |//  `.
 *                      /  \\|||  :  |||//  \
 *                     /  _||||| -:- |||||-  \
 *                     |   | \\\  -  /// |   |
 *                     | \_|  ''\---/''  |   |
 *                     \  .-\__  `-`  ___/-. /
 *                   ___`. .'  /--.--\  `. . __
 *                ."" '<  `.___\_<|>_/___.'  >'"".
 *               | | :  `- \`.;`\ _ /`;.`/ - ` : | |
 *               \  \ `-.   \_ __\ /__ _/   .-` /  /
 *          ======`-.____`-.___\_____/___.-`____.-'======
 *                             `=---='
 *          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 *                     佛祖保佑        永无BUG
 *            佛曰:
 *                   写字楼里写字间，写字间里程序员；
 *                   程序人员写程序，又拿程序换酒钱。
 *                   酒醒只在网上坐，酒醉还来网下眠；
 *                   酒醉酒醒日复日，网上网下年复年。
 *                   但愿老死电脑间，不愿鞠躬老板前；
 *                   奔驰宝马贵者趣，公交自行程序员。
 *                   别人笑我忒疯癫，我笑自己命太贱；
 *                   不见满街漂亮妹，哪个归得程序员？
 */
public class DailyTask implements IGPTAction {
    @Override
    public Map<String, String> invokeAction(String action, Map<String, String> params) {
        Map<String , String> result = new HashMap<>();
        if ("GET_JSON_STRING".equalsIgnoreCase(action)) {
            //将无效字符进行处理
            String jsonResult = params.get("jsonResult").replaceAll("\\s*|\r|\n|\t","");
            JSONObject resultJsonObject = null;
            try {
                //若全部生成JSON字符串，则不会进入catch
                resultJsonObject = JSON.parseObject(jsonResult);
            } catch (Exception ee) {
                //将"dayname"的上一个字符作为开始，以}]}字符作为结束，则最后需要+3
                jsonResult = jsonResult.substring(jsonResult.indexOf("\"dayName\"")-1 , jsonResult.indexOf("}]}")+3);
                resultJsonObject = JSON.parseObject(jsonResult);
            }
            //todo:new一个abq2_schedule_form基础资料
            //todo：新建的基础资料 其实每个字段都建好了，初始值都为null
            DynamicObject dynamicObject = BusinessDataServiceHelper.newDynamicObject("abq2_schedule_form");
            StringBuilder sb1 = new StringBuilder();
            for (int i = 1; i <= 10; i++) {
                int ascii = 48 + (int) (Math.random() * 9);
                char c = (char) ascii;
                sb1.append(c);
            }
            //设置对应属性
            dynamicObject.set("number", sb1.toString());
            dynamicObject.set("name", resultJsonObject.getString("dayName"));
            dynamicObject.set("status", "A");
            dynamicObject.set("enable", 1);
            dynamicObject.set("creator", RequestContext.get().getCurrUserId());

            //先获取新建的基础资料的单据体，再进行赋值
            DynamicObjectCollection dynamicObjectCollection = dynamicObject.getDynamicObjectCollection("abq2_task_entryentity");
            for (Object object : resultJsonObject.getJSONArray("dayTaskList")) {
                JSONObject jsonObjectSingle = (JSONObject) object;
                //新建的基础资料的单据体是没有任何分录的，要增加新的分录使用addNew
                DynamicObject dynamicObjectEntry = dynamicObjectCollection.addNew();
                //设置单据体中的数据值
                dynamicObjectEntry.set("abq2_task_context", jsonObjectSingle.getString("taskName"));
                dynamicObjectEntry.set("abq2_expect_minute", jsonObjectSingle.getString("finishMinutes"));
                dynamicObjectEntry.set("abq2_diff", jsonObjectSingle.getString("diff"));
            }
            //保存数据
            SaveServiceHelper.saveOperate("abq2_schedule_form", new DynamicObject[] {dynamicObject}, null);
            Long pkId = (Long) dynamicObject.getPkValue();
            //拼接URL字符串
            String targetForm = "bizAction://currentPage?gaiShow=1&selectedProcessNumber=processNumber&gaiAction=showBillForm&gaiParams={\"appId\":\"abq2_jic_s\",\"billFormId\":\"abq2_schedule_form\",\"billPkId\":\""+pkId+"\"}&title=日程安排 &iconType=bill&method=bizAction";
            System.out.println(targetForm);
            result.put("formUrl", targetForm);

            //将json数据处理后的信息返回给gpt提示，让gpt提示来处理
            result.put("resultJsonObject", resultJsonObject.toJSONString());
        }
        return result;
    }
}
